package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.ImMessage;
import com.example.service.ImMessageService;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {

    private Session session;
    private Long userId;


    private static ImMessageService webSocketMessageService;

    // 存储所有 WebSocketServer 实例，用于管理连接
    private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();


    @Autowired
    public void setWebSocketMessageService(ImMessageService webSocketMessageService) {
        WebSocketServer.webSocketMessageService = webSocketMessageService;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") Long userId) {
        log.info("WebSocket建立连接, 用户ID：{}", userId);
        this.session = session;
        this.userId = userId;
        webSocketSet.add(this);

        log.info("用户ID：{} 连接成功，当前在线人数为：{}", userId, webSocketSet.size());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("WebSocket连接关闭, 用户ID：{}", userId);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket发生错误, 用户ID：{}", userId);
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到客户端消息：{}", message);

        ImMessage msg = JSON.parseObject(message, ImMessage.class);


        webSocketMessageService.save(msg);

        // 发送消息给指定用户
        sendMessageToUser(msg);
    }

    // 发送消息给指定用户
    private void sendMessageToUser(ImMessage message) {
        Long toUserId = message.getToId();
        WebSocketServer targetWebSocket = findWebSocketByUserId(toUserId);
        if (targetWebSocket != null) {
            try {
                targetWebSocket.session.getBasicRemote().sendText(JSON.toJSONString(message));
                log.info("向用户ID：{} 发送消息成功：{}", toUserId, message);
            } catch (IOException e) {
                log.error("发送消息给用户ID：{} 失败：{}", toUserId, e.getMessage(), e);
            }
        } else {
            log.info("用户ID：{} 不在线，无法发送消息：{}", toUserId, JSON.toJSONString(message));
        }
    }

    // 根据 userId 查找对应的 WebSocketServer 实例
    private WebSocketServer findWebSocketByUserId(Long userId) {
        for (WebSocketServer webSocket : webSocketSet) {
            if (webSocket.userId.equals(userId)) {
                return webSocket;
            }
        }
        return null;
    }
}
